import { ref, shallowRef, watch } from 'vue'
import { useFileDialog } from '@vueuse/core'

/**
 * 单文件选择功能hook
 * @returns {*}
 */
export function useFileSelector() {
  const MIME_EXCEL =
    'application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.openxmlformats-officedocument.spreadsheetml.template'
  const { files, open, reset } = useFileDialog({
    multiple: false,
    accept: MIME_EXCEL
  })

  const selectedFile = shallowRef<any>(null)
  const selectedFileName = ref('')

  const callOpen = () => {
    open()
  }

  const removeFile = () => {
    reset()
  }

  watch(
    files,
    (newVal) => {
      if (newVal) {
        selectedFile.value = newVal[0]
        selectedFileName.value = newVal[0].name
      } else {
        selectedFile.value = null
        selectedFileName.value = ''
      }
    },
    {
      deep: true
    }
  )

  return {
    selectedFile,
    selectedFileName,
    callOpen,
    removeFile
  }
}
